import 'package:shared_preferences/shared_preferences.dart';

/// 货币数据模型
class CurrencyModel {
  final String code;
  final String symbol;
  final String name;

  const CurrencyModel({
    required this.code,
    required this.symbol,
    required this.name,
  });

  Map<String, dynamic> toJson() {
    return {
      'code': code,
      'symbol': symbol,
      'name': name,
    };
  }

  factory CurrencyModel.fromJson(Map<String, dynamic> json) {
    return CurrencyModel(
      code: json['code'] ?? '',
      symbol: json['symbol'] ?? '',
      name: json['name'] ?? '',
    );
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is CurrencyModel && other.code == code;
  }

  @override
  int get hashCode => code.hashCode;

  @override
  String toString() {
    return 'CurrencyModel(code: $code, symbol: $symbol, name: $name)';
  }
}

/// 货币变化监听器
typedef CurrencyChangeListener = void Function(CurrencyModel newCurrency, CurrencyModel oldCurrency);

/// 货币管理器 - 单例模式
class CurrencyManager {
  static CurrencyManager? _instance;
  static const String _currencyKey = 'selected_currency';
  
  // 货币变化监听器列表
  final List<CurrencyChangeListener> _listeners = [];
  
  // 防重复提示机制 - 记录最后一次通知的时间
  static DateTime? _lastNotificationTime;
  static const Duration _notificationCooldown = Duration(milliseconds: 500);
  
  // 私有构造函数
  CurrencyManager._();
  
  /// 获取单例实例
  static CurrencyManager get instance {
    _instance ??= CurrencyManager._();
    return _instance!;
  }
  
  /// 支持的货币列表
  static const List<CurrencyModel> supportedCurrencies = [
    CurrencyModel(code: 'USD', symbol: '\$', name: 'US Dollar'),
    CurrencyModel(code: 'EUR', symbol: '€', name: 'Euro'),
    CurrencyModel(code: 'GBP', symbol: '£', name: 'British Pound'),
    CurrencyModel(code: 'CAD', symbol: 'C\$', name: 'Canadian Dollar'),
    CurrencyModel(code: 'AUD', symbol: 'A\$', name: 'Australian Dollar'),
    CurrencyModel(code: 'PLN', symbol: 'zł', name: 'Polish Zloty'),
  ];
  
  /// 默认货币
  static const CurrencyModel defaultCurrency = CurrencyModel(
    code: 'USD',
    symbol: '\$',
    name: 'US Dollar',
  );
  
  CurrencyModel _currentCurrency = defaultCurrency;
  
  /// 获取当前选中的货币
  CurrencyModel get currentCurrency => _currentCurrency;
  
  /// 获取当前货币代码
  String get currentCurrencyCode => _currentCurrency.code;
  
  /// 获取当前货币符号
  String get currentCurrencySymbol => _currentCurrency.symbol;
  
  /// 获取当前货币名称
  String get currentCurrencyName => _currentCurrency.name;
  
  /// 获取格式化的货币显示文本 (例如: "USD,\$")
  String get formattedCurrencyDisplay => '${_currentCurrency.code},${_currentCurrency.symbol}';
  
  /// 添加货币变化监听器
  void addListener(CurrencyChangeListener listener) {
    if (!_listeners.contains(listener)) {
      _listeners.add(listener);
    }
  }
  
  /// 移除货币变化监听器
  void removeListener(CurrencyChangeListener listener) {
    _listeners.remove(listener);
  }
  
  /// 通知所有监听器货币已变化
  void _notifyListeners(CurrencyModel newCurrency, CurrencyModel oldCurrency) {
    // 记录通知时间
    _lastNotificationTime = DateTime.now();
    
    for (final listener in _listeners) {
      try {
        listener(newCurrency, oldCurrency);
      } catch (e) {
        print('Error in currency change listener: $e');
      }
    }
  }
  
  /// 检查是否应该显示货币切换通知（防止重复提示）
  static bool shouldShowNotification() {
    if (_lastNotificationTime == null) return true;
    
    final now = DateTime.now();
    final timeDiff = now.difference(_lastNotificationTime!);
    
    return timeDiff > _notificationCooldown;
  }
  
  /// 初始化货币管理器，从本地存储加载保存的货币
  Future<void> initialize() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final savedCurrencyCode = prefs.getString(_currencyKey);
      
      if (savedCurrencyCode != null) {
        final savedCurrency = supportedCurrencies.firstWhere(
          (currency) => currency.code == savedCurrencyCode,
          orElse: () => defaultCurrency,
        );
        _currentCurrency = savedCurrency;
      }
    } catch (e) {
      print('Error loading saved currency: $e');
      _currentCurrency = defaultCurrency;
    }
  }
  
  /// 设置当前货币
  Future<bool> setCurrency(CurrencyModel currency) async {
    try {
      // 检查是否为支持的货币
      if (!supportedCurrencies.contains(currency)) {
        print('Unsupported currency: ${currency.code}');
        return false;
      }
      
      // 检查货币是否真的改变了
      final oldCurrency = _currentCurrency;
      if (oldCurrency == currency) {
        print('Currency unchanged: ${currency.code}');
        return true; // 货币相同，不需要刷新
      }
      
      _currentCurrency = currency;
      
      // 保存到本地存储
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_currencyKey, currency.code);
      
      // 通知所有监听器货币已变化
      _notifyListeners(currency, oldCurrency);
      
      return true;
    } catch (e) {
      print('Error saving currency: $e');
      return false;
    }
  }
  
  /// 通过货币代码设置货币
  Future<bool> setCurrencyByCode(String currencyCode) async {
    try {
      final currency = supportedCurrencies.firstWhere(
        (currency) => currency.code == currencyCode,
        orElse: () => throw Exception('Currency not found'),
      );
      
      return await setCurrency(currency);
    } catch (e) {
      print('Error setting currency by code: $e');
      return false;
    }
  }
  
  /// 重置为默认货币
  Future<bool> resetToDefault() async {
    return await setCurrency(defaultCurrency);
  }
  
  /// 获取所有支持的货币
  List<CurrencyModel> getSupportedCurrencies() {
    return List.from(supportedCurrencies);
  }
  
  /// 检查是否为支持的货币
  bool isSupportedCurrency(String currencyCode) {
    return supportedCurrencies.any((currency) => currency.code == currencyCode);
  }
  
  /// 根据货币代码获取货币模型
  CurrencyModel? getCurrencyByCode(String currencyCode) {
    try {
      return supportedCurrencies.firstWhere(
        (currency) => currency.code == currencyCode,
      );
    } catch (e) {
      return null;
    }
  }
  
  /// 格式化价格显示
  String formatPrice(double price, {int decimalPlaces = 2}) {
    return '${_currentCurrency.symbol}${price.toStringAsFixed(decimalPlaces)}';
  }
  
  /// 清除保存的货币设置
  Future<bool> clearSavedCurrency() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_currencyKey);
      _currentCurrency = defaultCurrency;
      return true;
    } catch (e) {
      print('Error clearing saved currency: $e');
      return false;
    }
  }
}